<?php
/**
 * RssReaderApi
 *
 * presetns itself Rss Api
 * uses model Classes
 * contains all action in static functions
 * it allows to avoid creation of the object
 * in controllers
 * @author a.kuprienko
 *
 */
class Application_Model_RssReaderApi
{
	const ASSOC_ALLOW = true;
	const Prefix = 'Application_Model_DbTable_';
	//private $linkDB = new Application_Model_DbTable_Link();

	//***********Link model***********

	private static function getModel($modeName){
		$model  = self::Prefix.ucfirst($modeName);

		return new $model;
	}

	public static function addLink(array $data)
	{
		//$linkDB = new self::getModel('Link');

		return self::getModel('Link')->addRecord($data);
	}

	public static function updateLink(array $data, $id = null)
	{
		return self::getModel('Link')->saveById($data, $id);
	}

	public static function getLinks($id = null, $limit = null)
	{
		return self::getModel('Link')->getLinks($id, $limit);
	}

	public static function deleteLink($id)
	{
		return self::getModel('Link')->deleteByID((int)$id);
	}

	public static function getLink($id)
	{
		return self::getModel('Link')->getByID($id);
	}

	//***********Category model***********
	public static function getCategories($limit = null)
	{
		return self::getModel('Category')->getAll($limit);
	}


	public static function deleteCategory($id)
	{
		return self::getModel('Category')->deleteByID($id);
	}

	
	public static function updateCategory(array $data)
	{
		return self::getModel('Category')->saveByID($data);
	}

	
	public static function getCategoriesAssoc(){

		$categoryObjects = self::getModel('Category')->getAll();
		echo '<pre>';
		$i = 0;
		foreach($categoryObjects as $object){
			$categoryAssoc[$i]['key'] = $object->id;
			$categoryAssoc[$i]['value'] = $object->title;
			$i++;
		}

		return $categoryAssoc;
	}

	/**
	 *
	 *
	 * @param $id
	 */
	public function getCategory($id)
	{
		return self::getModel('Category')->getByID($id);
	}

	//***************news***********************
//	/**
//	 *
//	 * Enter description here ...
//	 * @param unknown_type $channel
//	 * @param unknown_type $linkID
//	 */
//	public static function addNews(Zend_Feed_Rss $channel, $linkID = null)
//	{
//		if(is_null($linkID)){
//			return false;
//		}
//		$updateDataRows = array();
//		$i = 0;
//		foreach ($channel as $feed){
//			$updateDataRows[$i]['description'] = $feed->description();
//			$updateDataRows[$i]['title'] = $feed->title();
//			$updateDataRows[$i]['full_news_link'] = $feed->link();
//			$updateDataRows[$i]['link_id'] = $linkID;
//			$i++;
//		}
//		return self::getModel('News')->addRecords($updateDataRows);
//	}


	public static function getLastFeed(){
		return Application_Model_RssReaderApi::getModel('Feed')->getLastRecord();
	}

	public static function getFirstFeed($linkID = null){
		return Application_Model_RssReaderApi::getModel('Feed')->getFirstRecord();
	}

	public static function getNews()
	{
		return self::getModel('Feed')->getAll();
	}

	/**
	 * make select of the last record
	 * for the link(RSS)(second param) then
	 * make search from the last
	 * feed of that news and keep
	 * downloading into base till it finds
	 * the simular record
	 *
	 * then this function add int base tag occurances(in case tere were new feeds)
	 * it's enough one time to add new feed to fullfill table feeds_tags
	 * $channelLinkID == link.title in links(table)
	 */
	public static function addNewFeeds(Zend_Feed_Rss $channel, $channelLinkID = null){
		//need last record of special link
		$lastFeed = Application_Model_RssReaderApi::getModel('Feed')->getLastRecord(array('link_id='=>$channelLinkID));
		$newFeeds = array();
		$insideIter = 0;

		$channelArray = self::channelIntoArray($channel);
		$feedNumber = count($channelArray);//in rss link
		$outsideIter = 0;
		//as criteria of adding new occurances into bd
		$flag = false;
		while($feedNumber > $outsideIter){
			$outsideIter++;
			$feed = $channelArray[$feedNumber-$outsideIter];
//			var_dump($feed->title());
//			var_dump($lastFeed->title);
//			var_dump($feed->title() != $lastFeed->title);
//			exit;
			if($feed->title() != $lastFeed->title){

				$flag = true;//a little bit fail:((itaration)
				$newFeeds[$insideIter]['description'] = $feed->description();
				$newFeeds[$insideIter]['title'] = $feed->title();
				$newFeeds[$insideIter]['full_news_link'] = $feed->link();
				$newFeeds[$insideIter]['link_id'] = $channelLinkID;
				$insideIter++;
				//!!!!!!!!!!need to optimise

			}else{
				break;
			}
		}
		$newFeedsTrueOrder = array_reverse($newFeeds);//becouse adding was from last feed
		self::getModel('Feed')->addRecords($newFeedsTrueOrder);
//		if($flag){
//			self::addTagOccurances();
//		}

	}

	/**
	 *
	 * transform Zend_Feed_Rss object
	 * to array of feeds
	 * @param Zend_Feed_Rss $channel
	 */
	private static function  channelIntoArray(Zend_Feed_Rss $channel)
	{
		$array = array();
		foreach($channel as $feed){
			$array[] = $feed;
		}
		return $array;
	}

	/**
	 * getKeyWordsOccurences()
	 *
	 * has fields: id, text(conctat(title,description)), link_id
	 * then in got field title.description AS text
	 * look for identity
	 * return  array of identities
	 * where  [iterator], key1=link_id, key2='news_id', key3 = 'tag' , key4='number'
	 * if no occurences
	 * it return null
	 * if keyword are null it will look for occerances by lall keywords from db
	 * @param $link_id
	 * @param array $keyWrords
	 * @return array $searchOutput( or null)
	 *
	 */
	public static function getKeyWordsOccurances(array $keyWords = null, $link_id = null ){

		if(is_null($keyWords)){
			$keyWords = array();
			$i = 0;
			//searching all keywords and transforming them into array
			foreach (self::getModel('Tag')->getAll() as $kword){
				$keyWords[$i++] = array(
					'title' => $kword->title,
					'id'    => $kword->id
				);
			}
		}
		/*
		 *  var $feeds is just array
		 *  $link_id is null it return all feeds of all links(rss)
		 */
		$feeds = self::getModel('Feed')->getFeedsText($link_id);
		$searchOutput = array();
		$i = 0;
		foreach($feeds as $feed){
			foreach($keyWords as $tag){
				//looking for occurences
				$occuranceNumber = substr_count($feed->text, $tag['title']);
				if($occuranceNumber > 0){
					$searchOutput[$i++] = array('link_id' => $feed->link_id,
												'feed_id' => $feed->id,
												'tag'     => $tag['title'],
												'tag_id'  => $tag['id'],
												'number'  => $occuranceNumber
												);
				}
			}
		}
		if(!empty($searchOutput)){
			return $searchOutput;
		}else{
			return null;
		}
	}


	/**
	 * $keywords which are a criteria for analising and adding into db
	 * they (on the current time) need to be equal NULL => searching by all keywords in all feeds;
	 * saving the quantity of occurances
	 * of tags into db
	 * this function is looking for some combination of feed_id.tag_id in db(table:feeds_tags)
	 * and then if there is no such comination it adds add occurances  
	 * @link http://ekimoff.ru/214/
	 */

	public static function addTagOccurances(array $keyWords = null){
		$tagOccurances =  self::getKeyWordsOccurances($keyWords);
		if(empty($tagOccurances)){
			return false;
		}
		$data = array();
		foreach ($tagOccurances as $tagOccurance){
			$combination = $tagOccurance['feed_id'].$tagOccurance['tag_id'];
			$hasDefeniteCombinationOfFeedTag = self::getModel('FeedTag')->
											   hasDefeniteCombinationOfFeedTag($combination);
			if(!$hasDefeniteCombinationOfFeedTag){

				$data['link_id'] = $tagOccurance['link_id'];
				$data['feed_id'] = $tagOccurance['feed_id'];
				$data['tag_id']  = $tagOccurance['tag_id'];
				$data['number']  = $tagOccurance['number'];
				self::getModel('FeedTag')->addRecord($data);
			}
		}
	}

	/**
	 * return cloud tags 
	 * in RowSet object or in array of array(if assoc param is true)
	 * has next fields(keys):tag, general_number, tag_id;
	 * @param  $link_id
	 * @param  $assocFlag
	 */
	public static function getCloudTags($link_id = null, $assocFlag = false)
	{
		$cloudTags =  self::getModel('FeedTag')->getTagsCloud($link_id);
		if($assocFlag == true){
			$cloudTagsAssoc = array();
			$i = 0;
			foreach ($cloudTags as $combination){
				$cloudTagsAssoc[$i++] = array('tag'            => $combination->tag,
											  'general_number' => $combination->general_number,
											  'tag_id'		   => $combination->tag_id
											  );
			}
			return $cloudTagsAssoc;
		}else{
			return $cloudTags;
		}
		
		
	}
	
	/**
	 * returns feeds with defenite tag occurances
	 * full description locates in Feed model
	 * @param $tagID
	 * @param $linkID
	 */
	public static function getFeedsByLinkIdWithCirtainTag($tagID = null, $linkID = null)
	{
		return self::getModel('Feed')->getFeedsByLinkIdWithCirtainTag($tagID, $linkID);
	} 
	
	
}